<script setup lang="ts">
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { toYuan, regYuanToFen } from '@/hooks/util'
import * as fishApi from '@/api/fishGoods'
import { message } from 'ant-design-vue'

const router = useRouter()

const myModal = ref()
const idList = ref<Array<string>>([])
const showModal = (list: Array<string>) => {
  idList.value = list
  myModal.value?.showModal()
}

defineExpose({
  showModal,
})

const emit = defineEmits<{
  refresh: []
}>()

let spinning = ref<boolean>(false)

const formRef = ref()
interface formState {
  sellingPrice?: number
  originalPrice?: number
  postage: number
}
const formState = ref<formState>({
  postage: 0,
})

import type { RuleObject } from 'ant-design-vue/es/form/interface'
let validateChangeBalance = async (rule: RuleObject, value: string) => {
  value = String(value)
  if (value == null || value.trim() === '') {
    return Promise.reject('金额不能为空')
  }
  // 使用正则表达式来验证金额格式，允许整数和小数点后两位
  const regex = /^\d+(\.\d{1,2})?$/
  if (!regex.test(value)) {
    return Promise.reject('请输入有效的金额（整数或小数点后两位）')
  }
  // 将字符串转换为数字并检查是否大于0
  const amount = parseFloat(value)
  if (isNaN(amount) || amount <= 0) {
    return Promise.reject('请输入大于0的金额')
  }
  // 如果一切正常，返回成功
  return Promise.resolve()
}

let validatePostage = async (rule: RuleObject, value: string) => {
  value = String(value)
  if (value == null || value.trim() === '') {
    return Promise.reject('金额不能为空')
  }
  // 使用正则表达式来验证金额格式，允许整数和小数点后两位
  const regex = /^\d+(\.\d{1,2})?$/
  if (!regex.test(value)) {
    return Promise.reject('请输入有效的金额（整数或小数点后两位）')
  }
  // 将字符串转换为数字并检查是否大于0
  const amount = parseFloat(value)
  if (isNaN(amount) || amount < 0) {
    return Promise.reject('请输入大于0的金额')
  }
  // 如果一切正常，返回成功
  return Promise.resolve()
}

import type { Rule } from 'ant-design-vue/es/form'
const rules: Record<string, Rule[]> = {
  sellingPrice: [{ required: true, validator: validateChangeBalance, trigger: 'blur' }],
  originalPrice: [{ required: true, validator: validateChangeBalance, trigger: 'blur' }],
  postage: [{ required: true, validator: validatePostage, trigger: 'blur' }],
}

const handleSubmit = async () => {
  formRef.value.validate().then(async () => {
    let param = {
      productIds: idList.value,
      originalPrice: regYuanToFen(formState.value.originalPrice as number, 100),
      sellingPrice: regYuanToFen(formState.value.sellingPrice as number, 100),
      transportFee: regYuanToFen(formState.value.postage as number, 100),
    }
    // console.log('param=', param)
    spinning.value = true
    try {
      let { state, message: msg } = await fishApi.batchProductChangePrice(param)
      if (state === 200) {
        message.success("任务已提交，请过1-3分钟后刷新查看")

      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
    spinning.value = false
    myModal.value.cancelModal()
  })
}
</script>

<template>
  <MyModal ref="myModal" title="批量改价">
    <template #content>
      <a-spin tip="Loading..." :spinning="spinning">
        <a-form ref="formRef" :rules="rules" :model="formState">
          <a-form-item has-feedback label="售价" name="sellingPrice">
            <a-input-number v-model:value="formState.sellingPrice" style="width: 100%"></a-input-number>
          </a-form-item>

          <a-form-item has-feedback label="原价" name="originalPrice">
            <a-input-number v-model:value="formState.originalPrice" style="width: 100%"></a-input-number>
          </a-form-item>

          <a-form-item has-feedback label="邮费" name="postage">
            <a-input-number v-model:value="formState.postage" style="width: 100%"></a-input-number>
          </a-form-item>

          <a-form-item style="text-align: right">
            <a-button @click="() => myModal.cancelModal()" style="margin-right: 10px">
              取消
            </a-button>
            <a-button type="primary" @click="handleSubmit">确定</a-button>
          </a-form-item>
        </a-form>
      </a-spin>
    </template>
  </MyModal>
</template>
